<template>
  <div class="add-warehouse-receiving">
    <div class="form-container">
      <div class="form-header">
        <h2 class="form-title">新增仓库入库</h2>
      </div>
      
      <form @submit.prevent="handleSubmit" class="warehouse-form">
        <!-- 货物名称 -->
        <div class="form-group">
          <label class="form-label required">货物名称</label>
          <input 
            v-model="formData.goodName" 
            type="text" 
            placeholder="请输入货物名称"
            class="form-input"
            required
          />
        </div>

        <!-- 支付方式 -->
        <div class="form-group">
          <label class="form-label required">支付方式</label>
          <div class="radio-group">
            <label class="radio-item">
              <input 
                v-model="formData.payway" 
                type="radio" 
                value="微信支付"
                class="radio-input"
              />
              <span class="radio-label">微信支付</span>
            </label>
            <label class="radio-item">
              <input 
                v-model="formData.payway" 
                type="radio" 
                value="支付宝支付"
                class="radio-input"
              />
              <span class="radio-label">支付宝支付</span>
            </label>
            <label class="radio-item">
              <input 
                v-model="formData.payway" 
                type="radio" 
                value="银联支付"
                class="radio-input"
              />
              <span class="radio-label">银联支付</span>
            </label>
            <label class="radio-item">
              <input 
                v-model="formData.payway" 
                type="radio" 
                value="银行转账"
                class="radio-input"
              />
              <span class="radio-label">银行转账</span>
            </label>
            <label class="radio-item">
              <input 
                v-model="formData.payway" 
                type="radio" 
                value="企业转账"
                class="radio-input"
              />
              <span class="radio-label">企业转账</span>
            </label>
            <label class="radio-item">
              <input 
                v-model="formData.payway" 
                type="radio" 
                value="线下支付"
                class="radio-input"
              />
              <span class="radio-label">线下支付</span>
            </label>
            <label class="radio-item">
              <input 
                v-model="formData.payway" 
                type="radio" 
                value="其它"
                class="radio-input"
              />
              <span class="radio-label">其它</span>
            </label>
          </div>
          <!-- 其它支付方式输入框 -->
          <input 
            v-if="formData.payway === '其它'"
            v-model="formData.otherPayway"
            type="text" 
            placeholder="请输入其他支付方式"
            class="form-input other-input"
          />
        </div>

        <!-- 类别类型和材质 -->
        <div class="form-row">
          <div class="form-group">
            <label class="form-label required">类别类型</label>
            <select v-model="formData.typeId" class="form-select" required :disabled="loadingTypes">
              <option value="">请选择类型</option>
              <option 
                v-for="type in typeOptions" 
                :key="type.id" 
                :value="type.id"
              >
                {{ type.typeName }}
              </option>
            </select>
            <div class="form-hint" v-if="loadingTypes">正在加载类型数据...</div>
            <div class="form-hint" v-else>类型: {{ typeOptions.map(t => t.typeName).join('、') }};</div>
          </div>

          <div class="form-group">
            <label class="form-label required">材质</label>
            <select v-model="formData.materialid" class="form-select" required :disabled="loadingMaterials">
              <option value="">请选择材质</option>
              <option 
                v-for="material in materialOptions" 
                :key="material.id" 
                :value="material.id"
              >
                {{ material.materialName }}
              </option>
            </select>
            <div class="form-hint" v-if="loadingMaterials">正在加载材质数据...</div>
            <div class="form-hint" v-else>材质: {{ materialOptions.map(m => m.materialName).join('、') }};</div>
          </div>
        </div>

        <!-- 规格 -->
        <div class="form-group">
          <label class="form-label">规格</label>
          <input 
            v-model="formData.specification" 
            type="text" 
            placeholder="请输入规格"
            class="form-input"
          />
        </div>

        <!-- 产地 -->
        <div class="form-group">
          <label class="form-label required">产地</label>
          <div class="location-group">
            <select v-model="formData.country" class="form-select" required>
              <option value="">请选择国家</option>
              <option value="中国">中国</option>
              <option value="美国">美国</option>
              <option value="日本">日本</option>
              <option value="德国">德国</option>
              <option value="韩国">韩国</option>
            </select>
            <select v-model="formData.province" class="form-select" required>
              <option value="">请选择省/州</option>
              <option v-if="formData.country === '中国'" value="上海市">上海市</option>
              <option v-if="formData.country === '中国'" value="北京市">北京市</option>
              <option v-if="formData.country === '中国'" value="广东省">广东省</option>
              <option v-if="formData.country === '中国'" value="江苏省">江苏省</option>
              <option v-if="formData.country === '中国'" value="浙江省">浙江省</option>
              <option v-if="formData.country === '美国'" value="加利福尼亚州">加利福尼亚州</option>
              <option v-if="formData.country === '美国'" value="纽约州">纽约州</option>
              <option v-if="formData.country === '日本'" value="东京都">东京都</option>
              <option v-if="formData.country === '日本'" value="大阪府">大阪府</option>
            </select>
          </div>
        </div>

        <!-- 仓库地址 -->
        <div class="form-group">
          <label class="form-label required">仓库地址</label>
          <input 
            v-model="formData.address" 
            type="text" 
            placeholder="请输入仓库地址"
            class="form-input"
            required
          />
        </div>

        <!-- 单价和数量 -->
        <div class="form-row">
          <div class="form-group">
            <label class="form-label required">单价</label>
            <input 
              v-model.number="formData.unitPrice" 
              type="number" 
              step="0.01"
              placeholder="请输入单价"
              class="form-input"
              required
            />
          </div>

          <div class="form-group">
            <label class="form-label required">数量</label>
            <div class="quantity-group">
              <button type="button" @click="decreaseQuantity" class="quantity-btn">-</button>
              <input 
                v-model.number="formData.quantity" 
                type="number" 
                min="1"
                placeholder="请输入数值"
                class="form-input quantity-input"
                required
              />
              <button type="button" @click="increaseQuantity" class="quantity-btn">+</button>
            </div>
          </div>
        </div>

        <!-- 采购金额显示 -->
        <div class="form-group amount-display">
          <label class="form-label">采购金额</label>
          <div class="amount-value">¥{{ formatAmount(purchaseAmount) }}</div>
        </div>

        <!-- 登记人 -->
        <div class="form-group">
          <label class="form-label required">登记人</label>
          <input 
            v-model="formData.registrant" 
            type="text" 
            placeholder="请输入登记人姓名"
            class="form-input"
            required
          />
        </div>

        <!-- 备注 -->
        <div class="form-group">
          <label class="form-label">备注</label>
          <textarea 
            v-model="formData.remark" 
            placeholder="请输入备注信息"
            class="form-textarea"
            rows="4"
          ></textarea>
        </div>

        <!-- 按钮组 -->
        <div class="form-actions">
          <button type="submit" class="btn btn-primary" :disabled="submitting">
            {{ submitting ? '提交中...' : '保存' }}
          </button>
          <button type="button" @click="handleCancel" class="btn btn-secondary">
            取消
          </button>
        </div>
      </form>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { materialApi } from '@/api'

const router = useRouter()
const submitting = ref(false)

// 类型数据
const typeOptions = ref<Array<{id: number, typeName: string}>>([])
const loadingTypes = ref(false)

// 材质数据
const materialOptions = ref<Array<{id: number, materialName: string}>>([])
const loadingMaterials = ref(false)

// 表单数据
const formData = reactive({
  goodName: '',
  payway: '',
  otherPayway: '',
  typeId: '',
  materialid: '',
  specification: '',
  country: '',
  province: '',
  address: '',
  unitPrice: 0,
  quantity: 1,
  registrant: '',
  remark: '',
  swNo: '' // 添加SwNo字段，为空让后端自动生成
})

// 获取类型数据
const fetchTypes = async () => {
  try {
    loadingTypes.value = true
    const response = await materialApi.getTypes()
    
    if (response.code === 200 && response.data) {
      typeOptions.value = response.data
    } else {
      console.error('获取类型数据失败:', response.message)
      // 如果API失败，使用默认数据
      typeOptions.value = [
        { id: 1, typeName: '车辆用品' },
        { id: 2, typeName: '办公用品' }
      ]
    }
  } catch (error) {
    console.error('获取类型数据出错:', error)
    // 如果API失败，使用默认数据
    typeOptions.value = [
      { id: 1, typeName: '车辆用品' },
      { id: 2, typeName: '办公用品' }
    ]
  } finally {
    loadingTypes.value = false
  }
}

// 获取材质数据
const fetchMaterials = async () => {
  try {
    loadingMaterials.value = true
    const response = await materialApi.getMaterials()
    
    if (response.code === 200 && response.data) {
      materialOptions.value = response.data
    } else {
      console.error('获取材质数据失败:', response.message)
      // 如果API失败，使用默认数据
      materialOptions.value = [
        { id: 1, materialName: '金属' },
        { id: 2, materialName: '橡胶' },
        { id: 3, materialName: '塑料' },
        { id: 4, materialName: '液体' },
        { id: 5, materialName: '纸质' }
      ]
    }
  } catch (error) {
    console.error('获取材质数据出错:', error)
    // 如果API失败，使用默认数据
    materialOptions.value = [
      { id: 1, materialName: '金属' },
      { id: 2, materialName: '橡胶' },
      { id: 3, materialName: '塑料' },
      { id: 4, materialName: '液体' },
      { id: 5, materialName: '纸质' }
    ]
  } finally {
    loadingMaterials.value = false
  }
}

// 组件挂载时获取数据
onMounted(() => {
  fetchTypes()
  fetchMaterials()
})

// 计算属性 - 产地组合
const placeofOrigin = computed(() => {
  if (formData.country && formData.province) {
    return `${formData.country}-${formData.province}`
  }
  return ''
})

// 计算属性 - 采购金额
const purchaseAmount = computed(() => {
  return formData.unitPrice * formData.quantity
})

// 方法
const increaseQuantity = () => {
  formData.quantity++
}

const decreaseQuantity = () => {
  if (formData.quantity > 1) {
    formData.quantity--
  }
}

// 格式化金额
const formatAmount = (amount: number) => {
  return amount.toLocaleString('zh-CN', {
    minimumFractionDigits: 2,
    maximumFractionDigits: 2
  })
}

// 获取当前时间
const getCurrentTime = () => {
  return new Date().toISOString()
}

const handleSubmit = async () => {
  try {
    submitting.value = true
    
    // 验证必填字段
    if (!formData.goodName) {
      alert('请输入货物名称')
      return
    }
    if (!formData.payway) {
      alert('请选择支付方式')
      return
    }
    if (!formData.typeId) {
      alert('请选择类别类型')
      return
    }
    if (!formData.materialid) {
      alert('请选择材质')
      return
    }
    if (!formData.country || !formData.province) {
      alert('请选择产地')
      return
    }
    if (!formData.address) {
      alert('请输入仓库地址')
      return
    }
    if (!formData.unitPrice || formData.unitPrice <= 0) {
      alert('请输入有效的单价')
      return
    }
    if (!formData.quantity || formData.quantity <= 0) {
      alert('请输入有效的数量')
      return
    }
    if (!formData.registrant) {
      alert('请输入登记人')
      return
    }

    // 构建提交数据，完全匹配API文档结构
    const submitData = {
      swNo: '', // 添加SwNo字段，为空让后端自动生成
      goodName: formData.goodName,
      payway: formData.payway === '其它' ? formData.otherPayway : formData.payway,
      typeId: parseInt(formData.typeId),
      materialid: parseInt(formData.materialid),
      specification: formData.specification,
      placeofOrigin: placeofOrigin.value,
      address: formData.address,
      quantity: formData.quantity,
      unitPrice: formData.unitPrice,
      remark: formData.remark,
      purchaseAmount: Math.round(purchaseAmount.value),
      registrant: formData.registrant,
      createdTime: getCurrentTime()
    }

    // 调用API接口
    const response = await materialApi.addWarehouseReceivingManagement(submitData)

    if (response.code === 200) {
      alert('提交成功！')
      router.push('/WarehouseReceiving')
    } else {
      alert('提交失败: ' + (response.message || '未知错误'))
    }
    
  } catch (error) {
    console.error('提交出错:', error)
    alert('提交出错，请重试')
  } finally {
    submitting.value = false
  }
}

const handleCancel = () => {
  if (confirm('确定要取消吗？未保存的数据将丢失。')) {
    router.push('/WarehouseReceiving')
  }
}
</script>

<style scoped>
.add-warehouse-receiving {
  padding: 20px;
  background-color: #f8f9fa;
  min-height: 100vh;
}

.form-container {
  max-width: 800px;
  margin: 0 auto;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
  overflow: hidden;
}

.form-header {
  background: #007bff;
  color: white;
  padding: 24px;
  text-align: center;
}

.form-title {
  margin: 0;
  font-size: 24px;
  font-weight: 600;
}

.warehouse-form {
  padding: 32px;
}

.form-group {
  margin-bottom: 24px;
}

.form-row {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 24px;
  margin-bottom: 24px;
}

.form-label {
  display: block;
  margin-bottom: 8px;
  font-weight: 500;
  color: #333;
  font-size: 14px;
}

.form-label.required::after {
  content: ' *';
  color: #dc3545;
}

.form-input, .form-select, .form-textarea {
  width: 100%;
  padding: 12px 16px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 14px;
  transition: border-color 0.2s;
  box-sizing: border-box;
}

.form-input:focus, .form-select:focus, .form-textarea:focus {
  outline: none;
  border-color: #007bff;
}

.form-textarea {
  resize: vertical;
  min-height: 100px;
  font-family: inherit;
}

/* 单选按钮组 */
.radio-group {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
  margin-bottom: 12px;
}

.radio-item {
  display: flex;
  align-items: center;
  cursor: pointer;
}

.radio-input {
  margin-right: 8px;
  width: 16px;
  height: 16px;
}

.radio-label {
  font-size: 14px;
  color: #333;
}

.other-input {
  margin-top: 12px;
}

/* 下拉选择框 */
.form-hint {
  margin-top: 6px;
  font-size: 12px;
  color: #666;
}

/* 产地选择 */
.location-group {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 16px;
}

/* 数量选择 */
.quantity-group {
  display: flex;
  align-items: center;
  gap: 8px;
}

.quantity-btn {
  width: 36px;
  height: 36px;
  border: 1px solid #ddd;
  background: white;
  cursor: pointer;
  font-size: 16px;
  font-weight: bold;
  color: #333;
  border-radius: 4px;
  transition: all 0.2s;
}

.quantity-btn:hover {
  background: #f8f9fa;
  border-color: #007bff;
}

.quantity-input {
  width: 100px;
  text-align: center;
}

/* 采购金额显示 */
.amount-display {
  background: #f8f9fa;
  padding: 16px;
  border-radius: 4px;
  border: 1px solid #e9ecef;
}

.amount-value {
  font-size: 20px;
  font-weight: 600;
  color: #007bff;
  text-align: center;
  margin-top: 8px;
}

/* 按钮样式 */
.form-actions {
  display: flex;
  gap: 16px;
  justify-content: center;
  margin-top: 32px;
  padding-top: 24px;
  border-top: 1px solid #e9ecef;
}

.btn {
  padding: 12px 24px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  font-weight: 500;
  transition: all 0.2s;
  min-width: 120px;
}

.btn-primary {
  background: #007bff;
  color: white;
}

.btn-primary:hover:not(:disabled) {
  background: #0056b3;
}

.btn-primary:disabled {
  background: #6c757d;
  cursor: not-allowed;
}

.btn-secondary {
  background: white;
  color: #333;
  border: 1px solid #ddd;
}

.btn-secondary:hover {
  background: #f8f9fa;
  border-color: #007bff;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .add-warehouse-receiving {
    padding: 10px;
  }
  
  .warehouse-form {
    padding: 20px;
  }
  
  .form-row {
    grid-template-columns: 1fr;
    gap: 16px;
  }
  
  .location-group {
    grid-template-columns: 1fr;
    gap: 12px;
  }
  
  .radio-group {
    flex-direction: column;
    gap: 12px;
  }
  
  .form-actions {
    flex-direction: column;
  }
  
  .btn {
    width: 100%;
  }
}
</style>
